package com.cskaoyan.order.biz.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //1 获取订单中的所以商品
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        //2 获取订单中商品的id
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        //3 判断商品id是否存储
        if (CollectionUtil.isEmpty(buyProductIds)){
            buyProductIds = cartProductDtoList.stream().map(CartProductDto::getProductId).collect(Collectors.toList());
        }
        //4 获取所以库存信息
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
        //5 判断库存是否初始化
        if (CollectionUtil.isEmpty(stocksForUpdate) || stocksForUpdate.size() != buyProductIds.size()){
            throw new BizException(OrderConstants.ORDER_INIT_FAIL,OrderConstants.ORDER_INIT_STOCK);
        }
        //6 判断购买数量是否超过限购数量
        for (Stock stock : stocksForUpdate) {
            List<CartProductDto> collect = cartProductDtoList.stream().filter(cartProductDto -> cartProductDto.getProductId().equals(stock.getItemId())).collect(Collectors.toList());
            if (collect.get(0).getProductNum() > stock.getRestrictCount()){
                throw new BizException(OrderConstants.ORDER_INIT_FAIL,OrderConstants.ORDER_STOCK_LIMIT);
            }
        }
        //7 对库存进行修改
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Stock stock = new Stock();
            stock.setItemId(cartProductDto.getProductId());
            stock.setLockCount(cartProductDto.getProductNum().intValue());
            stock.setStockCount(-cartProductDto.getProductNum());
            int count = stockMapper.updateStock(stock);
            //8 库存不足
            if (count == 0){
                throw new BizException(OrderConstants.ORDER_INIT_FAIL,OrderConstants.ORDER_STOCK_LACK);
            }
        }
        return true;
    }
}